package com.dodock.android.banglapapers.imageLoader;

import java.io.File;

import android.content.Context;
import android.os.Environment;

public class FileCache {

	private static File cacheDir;

	public FileCache(Context context) {
		// Find the dir to save cached images
		// if
		// (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		// cacheDir=new
		// File(android.os.Environment.getExternalStorageDirectory(),"TempImages");
		// else
		// cacheDir=context.getCacheDir();
		// if(!cacheDir.exists())
		// cacheDir.mkdirs();
		String rootDir = null;
        if ( Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // SD-card available
            rootDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/Android/data/" + context.getPackageName() + "/cache";
        } else {
            File internalCacheDir = context.getCacheDir();
            rootDir = internalCacheDir.getAbsolutePath();
        }
        setRootDir(rootDir);
	}
	
	 private void setRootDir(String rootDir) {
		 String name = "ImageCache";
		 String diskCacheDirectory = rootDir + IgnitedStrings.underscore(name.replaceAll("\\s", ""));
		 cacheDir = new File(diskCacheDirectory);
		 if (!cacheDir.exists()) {
			 cacheDir.mkdirs();
		 }
	 }
	
	 
	public File getFile(String url) {
		// String filename = String.valueOf(url.hashCode());
		String filename = getFileName(url);
		File f = new File(cacheDir, filename);
		return f;
	}

	public String getFileName(String strUrl) {
		 return strUrl.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
	}

	public static void clear() {
		if(cacheDir == null){
			return;
		}
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}

}